<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i>
                    {{pageTitle}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>

        <div class="container" :style="{'min-height': containerHeight + 'px'}">
            <div class="handle-box flex flex-center">
                <el-button type="primary" icon="el-icon-folder" @click="submitForm('ruleForm')">保存</el-button>
            </div>

            <div class="table-form-box">
                <h3 class="h3">开票申请单</h3>
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
                    <table border="0" width="100%" cellpadding="0" cellspacing="1">
                        <colgroup>
                            <col width="15%"/>
                            <col width="35%"/>
                            <col width="15%"/>
                            <col width="35%"/>
                        </colgroup>
                        <tbody>
                            <tr class="tr-title">
                                <td colspan="8">基本信息</td>
                            </tr>
                            <tr>
                                <td align="right">
                                   申请编号：
                                </td>
                                <td>
                                    <el-form-item prop="billingNo">
                                        <el-input
                                            v-model="ruleForm.billingNo"
                                            size="small"
                                            disabled
                                        ></el-input>
                                    </el-form-item>
                                </td>
                                <td align="right">
                                    <span class="color-ff2200">*</span>合同订单：
                                </td>
                                <td>
                                    <el-form-item prop="clientContractName">
                                        <div @click="showcontractDialog('合同')">
                                            <el-input
                                                placeholder="请输入"
                                                v-model="ruleForm.clientContractName"
                                                size="small"
                                                readonly
                                            >
                                                <i slot="suffix" class="el-icon-search"></i>
                                            </el-input>
                                        </div>
                                    </el-form-item>
                                </td>
                            </tr>
                            <tr>
                                <td align="right">
                                    客户:
                                </td>
                                <td>
                                    <el-form-item prop="clientName">
                                        <el-input
                                            placeholder="请输入"
                                            v-model="ruleForm.clientName"
                                            size="small"
                                            disabled
                                        >
                                        </el-input>
                                    </el-form-item>
                                </td>
                                <td align="right">
                                   责任人:
                                </td>
                                <td>
                                    <el-form-item prop="dutyName">
                                        <el-input
                                                placeholder="请输入"
                                                v-model="ruleForm.dutyName"
                                                size="small"
                                                disabled
                                            >
                                        </el-input>
                                    </el-form-item>
                                </td>
                            </tr>
                            <tr>
                                <td align="right">
                                    <span class="color-ff2200">*</span>开票日期：
                                </td>
                                <td>
                                    <el-form-item prop="billingOpenDate">
                                        <el-date-picker
                                            style="width:99%"
                                            v-model="ruleForm.billingOpenDate"
                                            align="right"
                                            type="date"
                                            placeholder="选择日期"
                                        ></el-date-picker>
                                    </el-form-item>
                                </td>
                                <td align="right">开票金额:</td>
                                <td>
                                    <el-form-item prop="billingOpenMoney">
                                        <el-input
                                            v-model="ruleForm.billingOpenMoney"
                                            size="small"
                                     
                                        ></el-input>
                                    </el-form-item>
                                </td>
                            </tr>
                            <tr>
                                <td align="right">金额大写:</td>
                                <td>
                                    <el-form-item prop="billingOpenBig">
                                        <el-input
                                            v-model="ruleForm.billingOpenBig"
                                            size="small"
                                            disabled
                                        ></el-input>
                                    </el-form-item>
                                </td>
                                <td align="right">结算余额:</td>
                                <td>
                                    <el-form-item prop="settlementBalance">
                                        <el-input
                                            v-model="ruleForm.settlementBalance"
                                            size="small"
                                     
                                        ></el-input>
                                    </el-form-item>
                                </td>
                            </tr>
                            <tr>
                                <td align="right">发票结余:</td>
                                <td>
                                    <el-form-item prop="invoiceBalance">
                                        <el-input
                                            v-model="ruleForm.invoiceBalance"
                                            size="small"
                                     
                                        ></el-input>
                                    </el-form-item>
                                </td>
                                <td align="right"><span class="color-ff2200">*</span>发票类型:</td>
                                <td> 
                                    <el-form-item prop="billingTypeName">
                                        <el-select
                                            v-model="ruleForm.billingTypeName"
                                            placeholder="请选择"
                                            @change="handleValue($event,'发票类型')"
                                        >
                                            <el-option
                                                v-for="(item, index) in billingTypeList"
                                                :key="index"
                                                :label="item.itemName"
                                                :value="item.id"
                                            ></el-option>
                                        </el-select>
                                    </el-form-item>
                                </td>
                            </tr>
                            <tr>
                                <td align="right">增值税信息:</td>
                                <td colspan="8">
                                    <el-form-item prop="vatInfo">
                                        <el-input v-model="ruleForm.vatInfo" type="textarea"></el-input>
                                    </el-form-item>
                                </td>
                            </tr>
                            <tr>
                                <td align="right">备注:</td>
                                <td colspan="8">
                                    <el-form-item prop="remark">
                                        <el-input v-model="ruleForm.remark" type="textarea"></el-input>
                                    </el-form-item>
                                </td>
                            </tr>
                            <tr>
                                <td align="right">财务开票：:</td>
                                <td colspan="8">
                                    <el-form-item prop="financialInvoicing">
                                        <el-input v-model="ruleForm.financialInvoicing" type="textarea"></el-input>
                                    </el-form-item>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </el-form>
            </div>

            <!-- 上传附件 -->
            <upload-files :files="fileList" @fun="dealFiles" v-if="flag"></upload-files>
        </div>
        <!-- 用户树搜索 -->
        <tree-search
            :isShow="showSearch"
            :dialogTitle="searchDialogTit"
            @edit="searchBack"
            @close="closeDialog"
        ></tree-search>
        <customer-search
            :isShow="showCustomerSearch"
            :dialogTitle="customerSearchDialogTit"
            method="clientInfoFindAllPageByDTO"
            @edit="customerSearchBack"
            @close="closeDialog"
        ></customer-search>
        <!-- 选择合同 -->
        <contract-search
            :isShow="showContractSearch"
            :dialogTitle="contractSearchDialogTit"
            method="clientContractInfoFindAllPageByDTO"
            @edit="contractSearchsearchBack"
            @close="closeDialog"
        ></contract-search>
    </div>
</template>

<script>
import appMain from '../../../utils/app_main';
import bus from '../../../components/common/bus'
 var checkPhone = (rule, value, callback) => {
    if (value !== '' && !(/^1[345789]\d{9}$/.test(value))) {
        callback(new Error('请输入正确的手机号'));
    } else{
        callback();
    }
    };
// var checkMoney = (rule, value, callback) => {
//     if(!/^(0|[1-9][0-9]*)$/.test(value)) {
//         callback(new Error('请输入正确的金额'));
//     } else{
//         callback();
//     }
// }
var checkMoney = (rule, value, callback) => {
    if(value !== '' && !/^(0|[1-9][0-9]*)$/.test(value)) {
        callback(new Error('请输入正确的金额'));
    } else{
        callback();
    }
}


export default {
    data() {
        return {
            pageTitle: '',
            containerHeight: '',
            
            ruleForm: {
                billingNo: '', // 开票编号	
                billingOpenBig: '', // 大写	
                billingOpenDate: '', // 开票日期	format: date-time
                billingOpenMoney: '', // 开票金额	format: int64
                billingTypeId: '', // 发票类型id	
                billingTypeName: '', // 发票类型名	
                clientContractId: '', // 合同ID	
                clientContractName: '', // 合同名称	
                clientContractNo: '', // 合同编码	
                clientId: '', // 往来客户ID	
                clientName: '', // 往来客户名	
                createTime: '', // 创建时间 format: date-time	
                dutyId: '', // 责任人id（往来单位中）	
                dutyName: '', // 责任人(往来单位中)	
                financialInvoicing: '', // 财务开票信息	
                flowNo: '', // 票流程编号	
                id: '', // 主键	
                invoiceBalance: '', // 发票结余	format: int64	
                remark: '', // 备注	
                settlementBalance: '', // 结算余额	format: int64
                status: '', // 流程状态	
                statusTypeId: '', // 表单类型ID	
                statusTypeName: '', // 表单类型名称	
                uploadReturns: [], // 附件上传详情	
                vatInfo: '', // 增值税信息
            },
            rules: {
                clientContractName:[{ required: true, message: '请选择合同', trigger: 'change' }],
                // clientName: [{ required: true, message: '请选择客户',  trigger: 'change'}],
                billingTypeName: [{ required: true, message: '请选择发票类型', trigger: 'change' }],
                billingOpenMoney: [{ validator: checkMoney, trigger: 'blur'}],
                invoiceBalance: [{ validator: checkMoney, trigger: 'blur'}],
                settlementBalance: [{ validator: checkMoney, trigger: 'blur'}],
               
            },
            fileList: [],
            isUpdate: false, //是否是更新
            flag: false,
            searchDialogTit: '',
            showSearch: false,
            contractSearchDialogTit: '',
            showContractSearch: false,
            customerSearchDialogTit: '',
            showCustomerSearch: false,

            // 下拉框
            billingTypeList: [] // 发票类型
        };
    },
    methods: {
        // 选择合同
        showcontractDialog(tit) {
            this.contractSearchDialogTit = tit;
            this.showContractSearch = true;
        },
        // 合同搜索结果返回
        contractSearchsearchBack(data) {
            console.log(data.backData, 'searchTreeBack');
            this.ruleForm.clientContractName = data.backData.clientContractName;
            this.ruleForm.clientContractId = data.backData.clientContractId;
            this.ruleForm.clientContractNo = data.backData.clientContractNo;
            this.ruleForm.clientId = data.backData.linkClientId
            this.ruleForm.clientName = data.backData.linkClientName
            this.ruleForm.dutyId =  data.backData.dutyUserId
             this.ruleForm.dutyName =  data.backData.dutyUserName
            this.showContractSearch = false;
        },
        // 选择姓名
        showTreeDialog(tit) {
            this.searchDialogTit = tit;
            this.showSearch = true;
        },
        //树组件搜索结果返回
        searchBack(data) {
            console.log(data.backData, 'searchTreeBack');
            this.query.dutyName = data.backData.name;
            this.query.dutyId = data.backData.id;
            this.showSearch = false;
        },
        closeTreeDialog(data) {
            this.showSearch = data.showDialog;
        },
        // 选择客户
        showCustomerDialog(tit) {
            this.customerSearchDialogTit = tit;
            this.showCustomerSearch = true;
        },
        // 客户搜索结果返回
        customerSearchBack(data) {
            console.log(data.backData, 'customerSearchBack');
            this.ruleForm.clientName = data.backData.name;
            this.ruleForm.clientId = data.backData.id;
            this.showCustomerSearch = false;
        },
        closeDialog (data) {
            this.showContractSearch = data.showDialog;
            this.showCustomerSearch = false
        },
        //新增
        billingInfoInsert() {
            appMain
                .billingInfoInsert(this.ruleForm)
                .then(res => {
                    if (res.data.code === 20000) {
                        bus.$emit('close_current_tags')
                        this.$message.success(res.data.message);
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        // 更新
        billingInfoUpdateById() {
            appMain
                .billingInfoUpdateById(this.ruleForm)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.$message.success(res.data.message);
                        bus.$emit('close_current_tags')
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        billingInfoFindById(id) {
            appMain
                .billingInfoFindById({}, id)
                .then(res => {
                    if (res.data.code === 20000) {
                        res.data.data.billingOpenMoney = res.data.data.billingOpenMoney || '';
                        res.data.data.invoiceBalance = res.data.data.invoiceBalance || '' 
                        res.data.data.settlementBalance = res.data.data.settlementBalance || '' 
                        this.ruleForm = res.data.data;
                    } else {
                        this.$message.error('服务器繁忙，请稍后再试');
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        //根据id查询附件
        uploadFileInfoFindById(id) {
            appMain
                .uploadFileInfoFindById({}, id)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.fileList = res.data.data;
                    } else {
                        this.$message.error(res.data.message);
                    }
                    this.flag = true;
                })
                .catch(err => {
                    console.log(err);
                });
        },
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.ruleForm.uploadReturns = this.fileList;
                    //alert('submit!');
                    if (!this.isUpdate) {
                        //添加文件列表
                        //新增
                        this.billingInfoInsert();
                    } else {
                        //添加文件列表
                        //更新
                        this.billingInfoUpdateById();
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        // 上传文件返回
        dealFiles(data) {
            this.fileList = data.backData;
            this.ruleForm.uploadReturns = this.fileList;
        },
         /**
         * 下拉框数据start
         */
        dictItemForPerfection () {
            let dictTypes =['发票类型'];
            dictTypes.map( item => {
                appMain.dictItem({ typeName: item }).then(res => {
                    if (res.data.code === 20000) {
                        if (item == '发票类型') {
                            this.billingTypeList = res.data.data;
                        }
                    } else {
                        this.$message.error(res.data.message);
                    }
                });
            })
        },
        //下拉框选取值
        handleValue(e, dict) {
            console.log(e, dict, '下拉框选取值');
            if (dict == '发票类型') {
                let item = this.selectChooseItem(this.billingTypeList, e);
                debugger
                this.ruleForm.billingTypeId = item.id;
                this.ruleForm.billingTypeName = item.itemName;
            }
        },
        // 通用字典选择
        selectChooseItem(item, id) {
            for (const key in item) {
                if (item[key].id == id) {
                    return item[key];
                }
            }
        },
        /**
         * 下拉框数据end
         */
    },

    mounted() {
        var div_height = window.screen.availHeight;
        var height = div_height - 100;
        this.containerHeight = height - 160;
        this.pageTitle = this.$router.currentRoute.meta.title;
        this.dictItemForPerfection();
    },
    created() {
        //如果有id过来就是修改的
        if (this.$route.query.id) {
            let id = this.$route.query.id;
            //是更新操作
            this.isUpdate = true;
            //通过id查询对应离职信息
            this.billingInfoFindById(id);
            //通过id查询附件信息
            this.uploadFileInfoFindById(id);
        } else {
            //新增操作
            this.isUpdate = false;
            this.flag = true;
        }
    }
};
</script>

<style  scoped>
.container {
    padding-bottom: 50px;
}
.handle-box {
    padding: 5px 50px;
    width: 100%;
    background-color: #fff;
    position: absolute;
    left: 0;
    bottom: 0px;
    border-bottom: 1px solid #ddd;
    border-top: 1px solid #ddd;
    z-index: 1;
}

.table-form-box table {
    background-color: #666;
}
.table-form-box .h3 {
    font-size: 22px;
    text-align: center;
    font-weight: normal;
    padding: 20px 0;
}
.table-form-box table .tr-title td {
    font-size: 14px;
    line-height: 40px;
}
.table-form-box table td,
.table-form-box table th {
    background-color: #fff;
    padding: 4px;
    min-height: 40px;
    font-size: 12px;
}
.color-ff2200 {
    color: #ff2200;
}
</style>